package krow.dev.weathertest;

import java.io.*;
import java.net.*;
import java.util.*;

import javax.xml.parsers.*;

import krow.dev.weathertest.MainActivity.*;

import org.w3c.dom.*;

import com.example.weathertest.*;

import android.app.*;
import android.content.*;
import android.os.*;
import android.util.*;
import android.view.*;
import android.view.WindowManager.LayoutParams;
import android.widget.*;

public class SubActivity extends Activity {
	ProgressDialog sProgress;
	UpdateThread sThread;
	String locate;
	
	EditText mEdit;
	ImageButton btn1;
	
	
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
		setContentView(R.layout.activity_info);
		Log.i("Sub", "서브 액티비티 접근");
		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);
		 
		mEdit = (EditText)findViewById(R.id.edit);
		
		btn1 = (ImageButton)findViewById(R.id.btn1);
		btn1.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				
				sProgress = new ProgressDialog(v.getContext());
				sProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
				sProgress.setTitle("업데이트");
				sProgress.setMessage("업데이트 중입니다..");
				sProgress.setCancelable(false);
				sProgress.setButton("취소", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						sThread.sQuit = true;
						sProgress.dismiss();
					}
				});
				sProgress.show();
				locate = mEdit.getText().toString();
				
				
				try{
					
					String locate2 = URLEncoder.encode(locate, "UTF-8");
					sThread = new UpdateThread("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.places%20where%20text=%22" + locate2 + "%22&format=xml");
					sThread.setDaemon(true);
					sThread.start();
				}
				catch(Exception e) {
					//Toast.makeText(Sub.this, e.getMessage(), Toast.LENGTH_SHORT).show();
				}
			}
		});
	}
	
	class PopupList {
		PopupList(String locate, String id, String countryName) {
			pLocate = locate;
			pID = id;
			pCountryName = countryName;
		}
		String pLocate;
		String pID;
		String pCountryName;
	}
	
	class MyListAdapter extends BaseAdapter {
		Context maincon;
		LayoutInflater Inflater;
		ArrayList<PopupList> arSrc;
		int layout;

		public MyListAdapter(Context context, int alayout, ArrayList<PopupList> aarSrc) {
			maincon = context;
			Inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			arSrc = aarSrc;
			layout = alayout;
			}

		public int getCount() {
			return arSrc.size();
			}

		public String getItem(int position) {
			return arSrc.get(position).pCountryName;
			
			}
		
		public String getItemwoeID(int position) {
			return arSrc.get(position).pID;
		}

		public long getItemId(int position) {
			return position;
			}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			final int pos = position;
			if (convertView == null) {
				convertView = Inflater.inflate(layout, parent, false);
				}
			
			TextView locateTxt = (TextView)convertView.findViewById(R.id.locateTextView);
			locateTxt.setText(arSrc.get(position).pCountryName);
			
			return convertView;
			}
		}

	
	class UpdateThread extends Thread {
		String mAddr;
		String mData; // 스레드를 통해 읽은 xml 문서 데이터
		
		String mDate; // xml <pubDate> 값 저장을 위한 변수
		String mDay; // xml <day> 값 저장을 위한 변수
		String wID; // id 저장을 위한 변수
		boolean sQuit;
		
		String stringTest; // 테스트용 변수
		
		String locateNameAttr;
		String locateName;
		
		String placeTypeNameAttr;
		String placeTypeName;
		
		//String admin1Attr, admin2Attr, admin3Attr, local1Attr, local2Attr;
		String country, admin1, admin2, admin3, local1, local2;
		
		ArrayList<String> arIDDataList; // 다중 woeID 저장용 어레이리스트
		ArrayList<String> arLocateNameList; // 다중 지역이름 저장용 어레이리스트
		ArrayList<String> arPlaceList; // 다중 지역 저장용 어레이리스트
		int x;
		
		UpdateThread(String addr) {
			mAddr = addr;
			mData = "";
			mDate = "";
			sQuit = false;
			
			stringTest = "";
			
			locateName = "";
			locateNameAttr = "";
			
			placeTypeNameAttr = "";
			placeTypeName = "";
			
			country = "";
			
			x = 0;
			arIDDataList = new ArrayList<String>();
			arLocateNameList = new ArrayList<String>();
			arPlaceList = new ArrayList<String>();
		}
		
		
		
		public void run() {
			//Toast.makeText(Sub.this, "서브2 스레드시작됨", Toast.LENGTH_SHORT).show();
			StringBuilder LocateXml = new StringBuilder();
			// 1. 쿼리를 통해 woeid값 빼내는 과정
			try{
				URL url = new URL(mAddr);
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				if (conn != null) {
					conn.setConnectTimeout(10000);
					conn.setUseCaches(false);
					if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
						BufferedReader br = new BufferedReader(
								new InputStreamReader(conn.getInputStream(), "UTF-8"));
						for (;;) {
							String line = br.readLine();
							if (line == null) {
								break;
							}
							LocateXml.append(line + '\n');
						}
						br.close();
						mData = LocateXml.toString();
					}
					conn.disconnect();
				}
				
				DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
				DocumentBuilder builder = factory.newDocumentBuilder();
				InputStream istream = new ByteArrayInputStream(mData.getBytes("utf-8"));
				Document doc = builder.parse(istream);
				
				Element upDate = doc.getDocumentElement();
				
				// 테스트중 
				NodeList placeItems = upDate.getElementsByTagName("place");
				
				
				
				for (int s = 0; s < placeItems.getLength(); s++) {  
					x += 1;
					Node itemNode = placeItems.item(s);
					
					if (itemNode.getNodeType() == Node.ELEMENT_NODE) {  
						  
					    Element itemElement = (Element)itemNode;  
					    
					   
					    
					    NodeList woeidNodeList = itemElement.getElementsByTagName("woeid");
					    Node woeidText = (woeidNodeList.item(0)).getFirstChild();
					    stringTest = woeidText.getNodeValue();
					    
					    NodeList cntryNodeList = itemElement.getElementsByTagName("country");
					    Node cntryText = (cntryNodeList.item(0)).getFirstChild();
					    country = cntryText.getNodeValue();
					    
					    arIDDataList.add(stringTest);
					    
					    NodeList admin1NodeList = itemElement.getElementsByTagName("admin1");
					    Node admin1Text = (admin1NodeList.item(0)).getFirstChild();
					    
					    NodeList admin2NodeList = itemElement.getElementsByTagName("admin2");
					    Node admin2Text = (admin2NodeList.item(0)).getFirstChild();
					    
					    NodeList admin3NodeList = itemElement.getElementsByTagName("admin3");
					    Node admin3Text = (admin3NodeList.item(0)).getFirstChild();
					    
					    if(admin1Text == null) {
					    	System.out.println("어드민1 못찾음");
					    	arLocateNameList.add(country);
					    }
					    else {
					    	System.out.println("어드민1 찾음");
					    	
					    	if(admin2Text == null) {
					    		System.out.println("어드민2 못찾음");
					    		admin1 = admin1Text.getNodeValue();
						    	arLocateNameList.add(country + ", " + admin1);
					    	}
					    	else {
					    		System.out.println("어드민2 찾음");
					    		
					    		if(admin3Text == null) {
					    			System.out.println("어드민3 못찾음");
					    			admin1 = admin1Text.getNodeValue();
						    		admin2 = admin2Text.getNodeValue();
						    		arLocateNameList.add(country + ", " + admin1 + ", " + admin2);
					    		}
					    		else {
					    			System.out.println("어드민3 찾음");
					    			admin1 = admin1Text.getNodeValue();
					    			admin2 = admin2Text.getNodeValue();
						    		admin3 = admin3Text.getNodeValue();
						    		arLocateNameList.add(country + ", " + admin1 + '\n' + admin2 + ", " + admin3);
					    		}
					    	}
					    	
					    }
					    
					}
				}
					   
					   
				
				
			}
			catch(Exception ex){}
			if(sQuit) {
				return;
			}
			
			
			mAfterDown.sendEmptyMessage(0);
			
		}
	}
	
	Handler mAfterDown = new Handler() {
		public void handleMessage(Message msg) {
			sProgress.dismiss();
			TextView mText1 = (TextView)findViewById(R.id.textview1);
			
			//int num = sThread.arIDDataList.size(); // ID어레이리스트 크기를 구함
			
			if( sThread.x == 0) { // ID어레이리스트에 값이 아예 안들어오면, 즉 woeID값 불러오기가 실패 됬을 경우 = 잘못된 지역명을 적을 시
				mText1.setText("틀린 지역명입니다. 다시 검색해주세요");
			}
			else if( sThread.x == 1 ) { // woeID값이 한 개인 지역일떄
				mText1.setText(sThread.wID);
				Intent intent = getIntent(); // 이 액티비티를 시작하게 한 인텐트를 호출
				intent.putExtra("data_ID", sThread.arIDDataList.get(0));
				intent.putExtra("data_LName", locate);
				setResult(RESULT_OK,intent); // 추가 정보를 넣은 후 다시 인텐트를 반환합니다.
				finish(); // 액티비티 종료
			}
			else if( sThread.x >= 2 ) { // woeID값이 두 개 이상의 지역 이름일때
				
				
				//Toast.makeText(Sub.this, sThread.arLocateNameList.get(0), Toast.LENGTH_LONG).show();
				ArrayList<PopupList> arItem = new ArrayList<PopupList>();
				PopupList pl;
			
				for(int i = 0; i < sThread.x ; i++) {
					pl = new PopupList(locate, sThread.arIDDataList.get(i), sThread.arLocateNameList.get(i));
					arItem.add(pl);
				}
			
				
				final MyListAdapter MyAdapter = new MyListAdapter(SubActivity.this, R.layout.popup_list_view, arItem);
				//ListView MyList = (ListView)findViewById(R.id.sub_listview);
				//MyList.setAdapter(MyAdapter);
				
				
				new AlertDialog.Builder(SubActivity.this)
	    		.setTitle("지역을 선택하세요")
	    		.setAdapter(MyAdapter, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						Intent intent = getIntent(); // 이 액티비티를 시작하게 한 인텐트를 호출
						intent.putExtra("data_ID", MyAdapter.getItemwoeID(which));
						intent.putExtra("data_LName", locate); //  MyAdapter.getItem(which) - 상세정보 띄우고싶으면 이거 이용
						setResult(RESULT_OK,intent); // 추가 정보를 넣은 후 다시 인텐트를 반환합니다.
						finish();
					}
				})
	    		
	    		.setPositiveButton("취소", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
					}
				})
	    		.show();

			}
			
		}
			
	};
	
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.actionbar_sub_menu, menu);

		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			this.onBackPressed();
			return true;
		
		case R.id.sub_info:
			new AlertDialog.Builder(this)
    		.setTitle("프로그램 소개")
    		.setMessage("야후날씨 API를 통한 날씨정보 어플임.")
    		.setIcon(R.drawable.ic_launcher)
    		.setPositiveButton("닫기", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
				}
			})
    		.show();
			return true;

		case R.id.sub_end:
			finish();
			System.exit(0);
			return true;
		}
		return false;
	}
}
